package com.tanhua.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.Admin;
import com.tanhua.model.vo.AdminVo;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    public Map login(String username, String password, String verificationCode, String uuid) {
        String code = redisTemplate.opsForValue().get(Constants.CAP_CODE +uuid);
        if (StringUtils.isEmpty(code) || !verificationCode.equalsIgnoreCase(code)) {
            throw new BusinessException("验证码有误");
        }
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername, username);
        Admin admin = adminMapper.selectOne(queryWrapper);
        if (admin == null) {
            throw new BusinessException("当前用户不存在");
        }
        password = DigestUtils.md5Hex(password);
        if (!admin.getPassword().equals(password)) {
            throw new BusinessException("密码错误");
        }
        Map map = new HashMap();
        map.put("id", admin.getId());
        String token = JwtUtils.getToken(map);
        Map tokenMap = new HashMap();
        tokenMap.put("token", token);
        return tokenMap;
    }

    public AdminVo profile() {
        Long userId = AdminHolder.getUserId();
        Admin admin = adminMapper.selectById(userId);
        AdminVo vo = AdminVo.init(admin);
        return vo;
    }
}
